package com.smart.web.listener;

import java.util.Random;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.smart.core.SpringContext;
import com.smart.model.User;
import com.smart.service.OnlineCountService;

/**
 * 1 创建匿名用户并放入session;
 * 2 记录在线人数
 */
public class SessionCreatedListener implements HttpSessionListener {
	
	private int onlineCount = 0;
	
	@Override
	public void sessionCreated(HttpSessionEvent se) {
		Random random = new Random();
		String s = "";
		for(int i=0; i<5; i++) {
			s += (random.nextInt(10) + "");
		}
		
		User user = new User();
		user.setName("游客" +s);
		user.setUsername(s);
		String ip = (String) se.getSession().getAttribute("clientIp");
		user.setIp(ip);
		se.getSession().setAttribute("anonyUser", user);
		
		synchronized(this) {
			onlineCount++;
			se.getSession().getServletContext().setAttribute("globalOnlineCount", onlineCount);
			OnlineCountService onlineCountService = SpringContext.getBean(OnlineCountService.class);
			onlineCountService.setCurrentOnlineCount(onlineCount);
		}
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		synchronized(this) {
			onlineCount--;
			se.getSession().getServletContext().setAttribute("globalOnlineCount", onlineCount);
			OnlineCountService onlineCountService = SpringContext.getBean(OnlineCountService.class);
			onlineCountService.setCurrentOnlineCount(onlineCount);
		}
	}
	
}
